<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\LibApi\PromoteController;
use App\Http\Controllers\LibApi\StickFigureController;
use App\Models\AccessNum;
use App\Models\AccessNumUser;
use App\Models\AppViewGray;
use App\Models\Banner;
use App\Models\Digital;
use App\Models\ResourceBusinessName;
use App\Models\ResourceReadingList;
use App\Models\ResourceReadRecom;
use App\Models\ResourceSystemType;
use App\Models\ResourceTotal;
use App\Models\ResourceTotalAccessNum;
use App\Models\ResourceTotalAccessNumUser;
use App\Models\ResourceType;
use App\Models\ResourceUserReadBook;
use Illuminate\Support\Facades\Cache;

/**
 * 微信首页
 */
class IndexController extends CommonController
{


    public function __construct()
    {
        parent::__construct();
    }


    /**
     * 首页
     * token 用户token 可有可无
     * big_type_id  数字资源大类id  (首页最上面显示的内容) 默认是推荐 0
     */
    public function index()
    {
        $big_type_id = $this->request->input('big_type_id', 0);
        $big_type_id = $big_type_id ?: 0;
        $user_id = $this->request->user_info['id'];

        $cache_key = md5($big_type_id . '_' . $user_id . '_index_data');
        $data = Cache::get($cache_key);
        if (empty($data)) {
            //只有当类型不存在才显示
            if (empty($big_type_id)) {
                if (!empty($user_id)) {
                    //获取历史阅读
                    // $resourceUserReadBookModel = new ResourceUserReadBook();
                    // $user_read_history = $resourceUserReadBookModel->getUserReadBookHistory(null, $user_id, null, 10);

                    //获取浏览记录（获取历史阅读）
                    $resourceTotalAccessNumUserModel = new ResourceTotalAccessNumUser();
                    $user_read_history = $resourceTotalAccessNumUserModel->getUserAccessNumResourceList($user_id, null, null, 6);
                    $i = 0;
                    $data['user_read_history'] = [];
                    foreach ($user_read_history['data'] as $val) {
                        $val['guid'] = $val['resource_guid']; //推荐
                        $val['is_recom'] = 2; //不是推荐
                        unset($val['intro']);
                        unset($val['resource_guid']);
                        $data['user_read_history'][$i] = $val;
                        $i++;
                    }
                    if (!empty($user_read_history['data']) && count($user_read_history['data']) < 5) {
                        //获取推荐的数字资源（最新上架）,补齐推荐
                        $resourceTotalModel = new ResourceTotal();
                        $resource_total = $resourceTotalModel->lists(null, null, $big_type_id, null,null, null, null, null, null, 3, null, 5);
                        foreach ($resource_total['data'] as $key => $val) {
                            $val['is_recom'] = 1; //推荐

                            unset($val['con_big_type']);
                            unset($val['resource_business_id']);
                            unset($val['big_type_id']);
                            unset($val['intro']);
                            $data['user_read_history'][$i] = $val;
                            $i++;
                        }
                    }
                }
                //获取对外数据资源大类
                // $resourceTypeModel = new ResourceType();
                // $resource_type = $resourceTypeModel->lists(['limit' => 10]);
                // $data['resource_type'] = $resource_type['data'];

                //数字资源
                $digitalModel = new Digital();
                $field = ['id', 'is_play', 'title', 'img',/*  'url', */ 'type_id', 'sort', 'browse_num', 'create_time'];
                $digital = $digitalModel->lists($field, null, null, 1, null, null, 'sort desc,id desc', 9);
                $data['digital'] = $digital['data'];

                //获取推荐阅读（书单形式数据）(最新一期)
                $resourceReadRecomModel = new ResourceReadRecom();
                $data['resource_read_recom'] = $resourceReadRecomModel->getNewReadRecomData();

                //获取推荐书单
                $resourceReadingListModel = new ResourceReadingList();
                $resource_reading_list = $resourceReadingListModel->getRecomReadingList(5);
                $data['resource_reading_list'] = $resource_reading_list['data'];

                $appViewGrayModel = new AppViewGray();
                $data['color']['is_gray'] = $appViewGrayModel->isViewGray(); //是否显示灰色
            }

            //以下是全显示

            //获取数字资源的banner
            // $resourceBannerModel = new ResourceBanner();
            // $resource_banner = $resourceBannerModel->lists(['is_play' => 1, 'limit' => 99]);
            // $data['resource_banner'] = $resource_banner['data'];

            $bannerModel = new Banner();
            $banner = $bannerModel->lists(null, null, $big_type_id, 1, null, 10);
            $data['banner'] = $banner['data'];

            //获取推荐的数字资源（最新上架） 推荐不显示，其余才显示
            if (!empty($big_type_id)) {
                $resource_type_info = ResourceType::where('id', $big_type_id)->first();
                if ($resource_type_info['is_show_new'] == 1) {
                    $resourceTotalModel = new ResourceTotal();
                    $resource_total = $resourceTotalModel->lists(null, null, $big_type_id, null, null,null, null, null, null, null, null, 6);
                    $data['resource_total_new'] = !empty($resource_total['data']) ? $this->disDataSameLevel($resource_total['data'], 'con_big_type', ['type_name' => 'big_type_name']) : null;
                }
            }
            //自定义模块
            // $resourceTotalTypeModel = new ResourceTotalType();
            // $resource_total_type = $resourceTotalTypeModel->getResourceTotalDataList($big_type_id, 10);
            // $data['resource_total_type'] = $resource_total_type;

            //系统栏目
            $resourceSystemTypeModel = new ResourceSystemType();
            $resource_system_type = $resourceSystemTypeModel->getResourceSystemDataList($big_type_id, 20);
            $data['resource_system_type'] = $resource_system_type;

            //以资源商显示数据,如果自定义分类太少在显示
            $data['resource_business_data'] = [];
            if (count($data['resource_system_type']) <= 10) {
                $resourceBusinessTypeModel = new ResourceBusinessName();
                $resource_business_data = $resourceBusinessTypeModel->getResourceBusinessDataList($big_type_id, 10);
                $data['resource_business_data'] = $resource_business_data;
            }
            //获取阅读榜单（推荐不返回）
            if (!empty($big_type_id)) {
                $resourceTotalAccessNumModel = new ResourceTotalAccessNum();
                // 视频单独返回
                if ($big_type_id != 3) {
                    if ($resource_type_info['is_show_read_list'] == 1) {
                        $resource_read_rank_week = $resourceTotalAccessNumModel->getReadAccessRank(null, null, 'week', null, $big_type_id, 6); //周榜
                        $resource_read_rank_month = $resourceTotalAccessNumModel->getReadAccessRank(null, null, 'month', null, $big_type_id, 6); //月榜
                        $resource_read_rank_year = $resourceTotalAccessNumModel->getReadAccessRank(null, null, 'year', null, $big_type_id, 6); //年榜
                        $data['resource_read_rank_week'] = $resource_read_rank_week['data'];
                        $data['resource_read_rank_month'] = $resource_read_rank_month['data'];
                        $data['resource_read_rank_year'] = $resource_read_rank_year['data'];
                    } else {
                        $data['resource_read_rank_week'] = null;
                        $data['resource_read_rank_month'] = null;
                        $data['resource_read_rank_year'] = null;
                    }
                } else {
                    //视频单独返回，热门播放
                    $resource_read_rank_all = $resourceTotalAccessNumModel->getReadAccessRank(null, null, null, null, $big_type_id, 6); //周榜
                    $data['resource_read_rank_all'] = $resource_read_rank_all['data'];
                }
            }

            Cache::put($cache_key, $data, 180); //缓存一分钟
        }


        //添加访问量
        $accessNumObj = new AccessNum();
        $accessNumObj->add(3);
        //添加单个用户访问量
        if (!empty($user_id)) {
            $accessNumUserObj = new AccessNumUser();
            $accessNumUserObj->addUserNum(3, $user_id);
        }

        return $this->returnApi(200, '获取成功', true, $data);
    }

    /**
     * 获取汇画首页资源
     * @param $big_type_id  数字资源大类id  (首页最上面显示的内容)  汇画 999
     */
    public function getPicturesData()
    {
        $big_type_id = $this->request->input('big_type_id', 0);
        if ($big_type_id != 999) {
            return $this->returnApi(201, '参数错误');
        }
        $stickFigureObj = new StickFigureController();
        $data = $stickFigureObj->getIndexData();
        if ($data['code'] == 200) {
            return $this->returnApi(200, '获取成功', true, $data['content']);
        }
        return $this->returnApi($data['code'], $data['msg']);
    }

    /**
     * 热门活动资源(获取悦读圈活动)
     * @param page 页数    默认第一页
     * @param limit 限制条数   默认 10 条
     */
    public function getActivityData()
    {
        $limit = $this->request->input('limit', 10);
        $page = $this->request->input('page', 1);

        $cache_key = md5($page . '_' . $limit . '_activity_data_external');
        $data = Cache::get($cache_key);
        if (empty($data)) {
            $promoteObj = new PromoteController();
            $data = $promoteObj->getReadInteractiveActivityList($page, $limit);
            Cache::put($cache_key, $data, 60); //缓存一分钟
        }

        if ($data['code'] == 200) {
            return $this->returnApi(200, '获取成功', true, $data['content']);
        }
        return $this->returnApi($data['code'], $data['msg']);
    }


    /**
     *获取备案号和版权信息
     */
    public function getCopyrightInfo()
    {
        $data['practice_number'] = '渝ICP备09007019号';
        // $data['copyright'] = '渝中区图书馆';
        return $this->returnApi(200, '获取成功', true, $data);
    }
}
